<?php
/**
 * User utils
 *
 * @author den
 */
//var_dump (Zend_Auth::getInstance()->getIdentity());
class Lemar_User
{
	/**
	 * Error messages
	 * @var array
	 */
	private static $_aErrorMessages = array();

	const LOG_EMAIL_ADMIN = "admin@dev.com";

//----------------------------------------------------------------------------------------------------


	/**
	 * User expired email
	 * @var string
	 */
	private static $_sExpiredEmail;

//----------------------------------------------------------------------------------------------------


	/**
	 * Checks if user is logged in
	 * @return bool
	 */
	public static function isLogged()
	{
		$oAuth = Zend_Auth::getInstance();
//		print_r($oAuth); die;
		if ($oAuth->hasIdentity())
		{
			$aIdentity = $oAuth->getIdentity();
			if ( !empty($aIdentity['User_id']) )
			{
				return true;
			}
		}
		else
		{
			return false;
		}
		// return Zend_Auth::getInstance()->hasIdentity();
	}

//----------------------------------------------------------------------------------------------------


	/**
	 * Returns logged user
	 * @return models_User|null
	 */
	public static function getLoggedUser()
	{
		// if (self::isLogged())
		// {
		//	$iUserId = Zend_Auth::getInstance()->getIdentity();
		//	return models_UserMapper::findById($iUserId);
		//}
		//return null;

		if (self::isLogged())
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			return models_UserMapper::findById($aIdentity['User_id']);
		}
		return null;
	}

//----------------------------------------------------------------------------------------------------


	/**
	 * Returns logged user id
	 * @return int|null
	 */
	public static function getLoggedUserId()
	{
		if (self::isLogged())
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			return $aIdentity['User_id'];
		}
		else
		{
			return null;
		}
	}

//----------------------------------------------------------------------------------------------------


	/**
	 * Sets user logged in
	 *
	 * @param int $iUserId
	 */
	public static function setLogged($iUserId)
	{
		if ( !self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			$aIdentity['User_id'] = $iUserId;
			$oAuthStorage = Zend_Auth::getInstance()->getStorage();
			$oAuthStorage->write($aIdentity);
			models_UserMapper::updateSessionId($iUserId, Zend_Session::getId());
		}
	}

//----------------------------------------------------------------------------------------------------


	/**
	 * Performs user logout
	 *
	 */
	public static function logout()
	{
		if ( self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			unset($aIdentity['User_id']);
			$oAuthStorage = Zend_Auth::getInstance()->getStorage();
			$oAuthStorage->write($aIdentity);

			$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
			unset($oZendSession->iWeddingId);
		}
		// Zend_Auth::getInstance()->clearIdentity();
		// Zend_Session::destroy();
	}

//----------------------------------------------------------------------------------------------------


	/**
	 * Returns trial days left
	 *
	 * @param int $iUserId
	 * @return int
	 */
	public static function getTrialLeft($iUserId = null)
	{
		$oUser = (null === $iUserId) ? self::getLoggedUser() : models_UserMapper::findById($iUserId);
		if (null === $oUser)
		{
			return null;
		}

		$oConfig = Zend_Registry::getInstance()->get('config')->user;
		$iTrialDays = (int) $oConfig->trial;

		$iDaysDiff = Lemar_Date::getDatesDiff(Lemar_Date::getCurrentDate(Lemar_Date::MYSQL_DATETIME), $oUser->getRegistrationDateTime(), Lemar_Date::MYSQL_DATETIME, Lemar_Date::MYSQL_DATETIME);

		return ($iTrialDays - $iDaysDiff);
	}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------


    /**
     * Returns wedding days left
     *
     * @param models_Wedding $oWedding
     * @return int
     * @author Nikita
     */
    public static function getEventsLeft(models_Wedding $oWedding)
    {
    	$aEvents = array();
        $aEvent = models_EventMapper::findByWeddingIdAndColumn($oWedding->getId(), 'is_dashboard','yes');

        foreach ($aEvent as $iIndex => $oEvent)
        {
			$aEvents[$iIndex]['days'] = Lemar_Date::getDatesDiff($oEvent->getDate(), Lemar_Date::getCurrentDate());
			$aEvents[$iIndex]['name'] = $oEvent->getName();
			$aEvents[$iIndex]['id'] = $oEvent->getId();
        }
        return $aEvents;
    }

//----------------------------------------------------------------------------------------------------


    /**
     * Returns wedding days left
     *
     * @author bigjohn
     *
     * @return array|null
     */
    public static function getTrialUsers()
    {
		$aUsers = models_UserMapper::fetchTrial();
		if (null === $aUsers)
		{
			return null;
		}
		return $aUsers;
    }

//----------------------------------------------------------------------------------------------------


    /**
     * Performs user registration
     *
     * @param Zend_Form $oForm
     * @param array $aPost
     * @throws Lemar_Exception
     */
    public static function doRegister(Zend_Form $oForm, $aPost)
    {
//		print_r($oForm->isValid($aPost));
//die;
    	if ($oForm->isValid($aPost))
		{
			$sRegistrationDateTime = Lemar_Date::getCurrentDate(Lemar_Date::MYSQL_DATETIME);
			$oUser = new models_User();
			$oUser->email	 				= $oForm->getValue('email');
			$oUser->password			 	= $oForm->getValue('password');
			$oUser->firstName 				= $oForm->getValue('first_name');
			$oUser->lastName 				= $oForm->getValue('last_name');
			$oUser->registrationDatetime	= $sRegistrationDateTime;

			$iUserId = models_UserMapper::save($oUser);
			if ($iUserId)
			{
				$url = $_SERVER["HTTP_HOST"];
				$body = 'Welcome!';

				$subject = 'Welcome message';

				self::send($body, $oForm->getValue('email'), $subject, self::LOG_EMAIL_ADMIN);
			}
			self::setLogged($iUserId);
			return true;
		}
		else
		{
			self::setErrorMessages(Lemar_Form::getErrorMessages($oForm));
			throw new Lemar_Exception();
		}
    }

//----------------------------------------------------------------------------------------------------

	public static function send($body, $address, $subject, $from)
	{

		$transport = new Zend_Mail_Transport_Smtp();

		$mail = new Zend_Mail();
		$mail->setBodyText(strip_tags($body));
		$mail->setBodyHtml(nl2br($body));
		$mail->addTo($address);
		$mail->setSubject($subject);
		$mail->setFrom($from, NULL);

		$mail->send($transport);


	}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------


	/**
     * Performs user login
     *
     * @param Zend_Form $oForm
     * @param array $aPost
     * @param bool $bRememberMe
     * @throws Lemar_Exception|Lemar_AccountExpiredException
     */
    public static function doLogin(Zend_Form $oForm, $aPost, $bRememberMe)
    {
		if ($oForm->isValid($aPost))
		{
			$oDbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
			$oAuthAdapter = new Zend_Auth_Adapter_DbTable($oDbAdapter);
			$oAuthAdapter->setTableName('user')
			             ->setIdentityColumn('email')
			             ->setCredentialColumn('password');

			$oAuthAdapter->setIdentity($oForm->getValue('email'))
			             ->setCredential($oForm->getValue('password'));

			$oResult = $oAuthAdapter->authenticate();


			if (! $oResult->isValid())
			{
				/** Auth doesn't have own translator. Uses translators directly */
				/* @var $oTranslate Zend_Translate */
				$oTranslate = Zend_Registry::get('Zend_Translate');

				$aAuthErrorMessages = array();

				$sControlIndex = (Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID == $oResult->getCode()) ? 'password' : 'email';

				$aAuthErrorMessages[0][] = 'user';
				$aAuthErrorMessages[0][] = 'login information is invalid';
				$aAuthErrorMessages[0][] = 'error';

				self::setErrorMessages($aAuthErrorMessages);
				throw new Lemar_Exception();
			}
			else
			{
				// Store auth object in storage (in session by default)
				$stdClassUser = $oAuthAdapter->getResultRowObject();
				Lemar_User::setLogged($stdClassUser->id);


				$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
				$oZendSession->errorMessage = '';

				if ($bRememberMe)
				{
					Zend_Session::rememberMe();
				}

			}
		}
		else
		{
				$aAuthErrorMessages[0][] = 'user';
				$aAuthErrorMessages[0][] = 'user ' . $aPost['email'] . ' is not registered';
				$aAuthErrorMessages[0][] = 'error';

				self::setErrorMessages($aAuthErrorMessages);
			throw new Lemar_Exception();
		}
    }

//----------------------------------------------------------------------------------------------------


    public static function setExpiredEmail($sExpiredEmail)
    {
		self::$_sExpiredEmail = $sExpiredEmail;
    }

//----------------------------------------------------------------------------------------------------

    public static function getExpiredEmail()
    {
		return self::$_sExpiredEmail;
    }

//----------------------------------------------------------------------------------------------------

    public static function getErrorMessages()
    {
    	return self::$_aErrorMessages;
    }

//----------------------------------------------------------------------------------------------------


    public static function setErrorMessages($aErrorMessages)
    {
    	self::$_aErrorMessages = $aErrorMessages;
    }

//----------------------------------------------------------------------------------------------------


	/**
	 * Checks if user already paid
	 *
	 * @param string $sUserEmail
	 * @return bool
	 */
	public static function isAlreadyPaid($sUserEmail)
	{
		$oUser = models_UserMapper::findByEmail($sUserEmail);
		return (null === $oUser) ? false : ('full' == $oUser->getAccountType());
	}

//----------------------------------------------------------------------------------------------------


} //   CLASS